# @Time : 2025-01-11 16:37
# @Author : Fioman 
# @Phone : 13149920693
import threading
import time

import gevent

from common.produce_logger import debug_produce
from drivers.plc_modbus_base import PlcModbusBase
from personal_tool.data_result import DataResult

"""
收板机plc类,单例类
"""


class LoaderPlc(PlcModbusBase):
    _lock = threading.Lock()
    _instance = None
    _initFlag = False

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            with cls._lock:
                cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        if not self._initFlag:
            self.ip = "192.168.1.88"
            self.port = 502
            self._initFlag = True
            super().__init__(self.ip, self.port)
            debug_produce(f"LoaderPlc.__init__() 初始化成功")

    def write_board_length_and_plan_count(self, length: float, width: float, planCount: int) -> DataResult:
        """
        写入板长
        @ param length: 板长
        """
        countAddress = 4000
        lengthAddress = 4002
        widthAddress = 4004
        self.write_float_use_builder(widthAddress, width)
        self.write_word(countAddress, planCount)
        return self.write_float_use_builder(lengthAddress, round(length, 2))

    def get_loader_plc_state(self) -> DataResult:
        """
        检查PLC是否在线
        """
        readAddress = 70
        return self.read_word(readAddress)

    def get_loader_plc_finished(self) -> DataResult:
        """
        获取loaderPLC的数量
        """
        readAddress = 4512
        return self.read_word(readAddress)

    def request_change_order(self):
        """
        writeAddress
        :return:
        """
        writeAddress = 4050
        return self.write_word(writeAddress, 1)

    def clear_request_change_order(self):
        """
        清除4050信号
        """
        writeAddress = 4050
        return self.write_word(writeAddress, 0)

    def get_allow_change_order(self):
        readPos = 4550
        return self.read_word(readPos)


if __name__ == '__main__':
    loaderPlc = LoaderPlc()
    connect = loaderPlc.connect()
    if not connect:
        print('plc连接失败')
    else:
        print("plc连接成功")

    result = loaderPlc.get_loader_plc_state()
    if result.state:
        print(f"plc状态获取成功: 状态为:{result.data}")
    else:
        print(f"plc状态获取失败: {result.info}")

    result = loaderPlc.request_change_order()
    if not result.state:
        print(f"plc工单请求下发失败: {result.info}")
    else:
        print(f"plc工单请求下发成功")
    start = time.time()
    errorInfo = ""
    while True:
        if time.time() - start > 5:
            print(errorInfo)
            break
        result = loaderPlc.get_allow_change_order()
        if not result.state:
            errorInfo = result.info
            gevent.sleep(0.2)
            continue
        if result.data == 1:
            print("收到允许下发")
        elif result.data == 2:
            errorInfo = "有板异常"
        elif result.data == 3:
            errorInfo = "尺寸异常"
        elif result.data == 4:
            errorInfo = "脱机状态"
        else:
            errorInfo = f"未知错误码,错误码为:{result.data}"
        gevent.sleep(0.2)
        continue

        # 下发当前工单的板长和数量
    result = loaderPlc.write_board_length_and_plan_count(123.45, 234.56, 8888)
    if result.state:
        print("板长和数量下发成功")
    else:
        print("板长和数量下发失败")
